import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.resps.ScanResult;
import redis.clients.jedis.resps.Tuple;

import java.util.List;

/**
 * jedis 操作 redis zset基本命令
 */
public class RedisDemoZset {
    public static void test1(Jedis jedis) {
        System.out.println("zadd 和 zrange");
        jedis.flushDB();

        jedis.zadd("key",10.0, "zhangsan");
        jedis.zadd("key",20.0, "lisi");
        jedis.zadd("key",30.0, "wangwu");
        List<String> result = jedis.zrange("key", 0, -1);
        System.out.println("result: " + result);

        List<Tuple> ret = jedis.zrangeWithScores("key", 0, -1);
        for (int i = 0; i < ret.size(); i++) {
            System.out.println("element: " + ret.get(i).getElement() + ", score: " + ret.get(i).getScore());
        }
    }
    public static void test2(Jedis jedis) {
        System.out.println("zcard 和 zrem");
        jedis.flushDB();

        jedis.zadd("key",10.0, "zhangsan");
        jedis.zadd("key",20.0, "lisi");
        jedis.zadd("key",30.0, "wangwu");
        long len = jedis.zcard("key");
        System.out.println("len: " + len);

        jedis.zrem("key", "zhangsan", "lisi");

        len = jedis.zcard("key");
        System.out.println("len: " + len);
    }
    public static void test3(Jedis jedis) {
        System.out.println("score");
        jedis.flushDB();

        jedis.zadd("key",10.0, "zhangsan");
        jedis.zadd("key",20.0, "lisi");
        jedis.zadd("key",30.0, "wangwu");

        Double zscore = jedis.zscore("key", "zhangsan");
        System.out.println("zscore: " + zscore);

        zscore = jedis.zscore("key", "zhangsan2");
        System.out.println("zscore: " + zscore);

        zscore = jedis.zscore("key", "wangwu");
        System.out.println("zscore: " + zscore);
    }
    public static void test4(Jedis jedis) {
        System.out.println("zrank");
        jedis.flushDB();

        jedis.zadd("key",10.0, "zhangsan");
        jedis.zadd("key",20.0, "lisi");
        jedis.zadd("key",30.0, "wangwu");
        Long index = jedis.zrank("key", "wangwu");
        System.out.println("index: " + index);
        index = jedis.zrank("key", "wangwu2");
        System.out.println("index: " + index);

    }
    public static void main(String[] args) {
        JedisPool jedisPool = new JedisPool("tcp://127.0.0.1:8888");
        try(Jedis jedis = jedisPool.getResource()) {
            // test1(jedis);
            // test2(jedis);
            // test3(jedis);
            test4(jedis);

        }
    }
}
